package cn.itcast.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

@Component
public class baidudituController {

    static String AK = "14fN9rWBjnBw4LGzGe7PVNtf"; // 百度地图密钥

    public static void main(String[] args) {
        String dom = "广东省东莞市南城街道袁屋边金钟坊1号";
        System.out.println("'" + dom + "'的经纬度为：" + getCoordinate(dom));
    }

    // 调用百度地图API根据地址，获取坐标
    public static Map<String,Double> getCoordinate(String address) {
        if (address != null && !"".equals(address)) {
            String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + AK;
            String json = loadJSON(url);
            if (json != null && !"".equals(json)) {
                //JSONObject obj = JSONObject.fromObject(json);
                JSONObject obj = JSON.parseObject(json);
                if ("0".equals(obj.getString("status"))) {
                    double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng"); // 经度
                    double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat"); // 纬度
                    Map<String,Double> map = new HashMap<String, Double>();
                    map.put("lng",lng);
                    map.put("lat",lat);
                    return map;
                }
            }
        }
        return null;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            System.out.println(yc.getInputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }


}
